<?php
namespace App\Admin\Controllers\Stocking;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysIArea;
use App\Models\Product\ProductClassify;
use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\Stocking\StockingSkuLog;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;
class SkuLogController extends AdminController{

    protected $title = '备货审批记录';

    protected function grid()
    {
        $grid = new Grid(new StockingSkuLog());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('skuClassify.title','品类')->totalRow('汇总');
        $grid->column('area.area','站点');
        $grid->column('sku.psku_code','SKU');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('ratio','销售比例')->display(function ($value){
            return ($value && $value > 0) ? $value * 100 . '%' : "<span style='color: red'>null</span>";
        });
        $grid->column('fba_instant_num','FBA在库')->totalRow();
        $grid->column('fba_transit_num','FBA在途')->totalRow();
        $grid->column('cn_instant_num','国内在库')->totalRow();
        $grid->column('cn_transit_num','国内在途')->totalRow();
        $grid->column('os_instant_num','海外仓在库')->totalRow();
        $grid->column('os_transit_num','海外仓在途')->totalRow();
        $grid->column('apply_num','备货数量')->totalRow();
        $grid->column('apply_remark','申请备注');
        $grid->column('approval_num','审批数量')->totalRow();
        $grid->column('approval_remark','审批备注');
        $grid->column('seller_id','备货员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('approval_date','审批日期');
        for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
            $grid->column('estimate_num'.$i,'预估'.$i)->totalRow();
        }

        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('stocking/sku-log-download'));
        });
        //if(!Admin::user()->can('stocking.sku-approval')){
            $grid->disableRowSelector();
        //}
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->fixColumns(4,0);
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('area_id','站点')->select(SysIArea::options());
                $filter->between('approval_date', '审批日期')->date();
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
        });

        return $grid;
    }

    public function destroy($id){
        $ids = explode(',', $id);
        if (StockingSkuLog::destroy(array_filter($ids))) {
            $data = [
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ];
        } else {
            $data = [
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ];
        }
        return response()->json($data);
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = StockingSkuLog::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if($key == 'approval_date'){
                if(isset($_filter['start'])&&$_filter['start']){
                    $query->where('approval_date','>=',$_filter['start']);
                }
                if(isset($_filter['end'])&&$_filter['end']){
                    $query->where('approval_date','<=',$_filter['end']);
                }
            }
            if(in_array($key,['area_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head1 = ['品类','站点','SKU','季节性','产品名称','销售比例',
            'FBA在库','FBA在途', '国内在库','国内在途', '海外仓在库','海外仓在途',
            '备货数量','备货原因','审批数量','审批原因','备货员','审批日期'];
        $head2 = [];
        for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
            $head2[] = '预估'.$i;
        }
        $head = array_merge($head1,$head2);
        RExcel::exportCsv('备货审批记录',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->seller_id ?: 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $data1 = [
                $model->skuClassify->title ?? '',
                $model->area->area ?? '',
                $model->sku->psku_code ?? '',
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->sku->psku_cn ?? '',
                $model->ratio,
                $model->fba_instant_num ?: 0,
                $model->fba_transit_num ?: 0,
                $model->cn_instant_num ?: 0,
                $model->cn_transit_num ?: 0,
                $model->os_instant_num ?: 0,
                $model->os_transit_num ?: 0,
                $model->apply_num,
                $model->apply_remark,
                $model->approval_num,
                $model->approval_remark,
                $seller[$sellerId],
                $model->approval_date,
            ];
            $data2 = [];
            for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
                $data2[] = $model->{"estimate_num$i"} ?: 0;
            }
            $temp = array_merge($data1,$data2);
            yield $temp;
        }
    }
}
